import copy
import datetime
import threading
from typing import Optional

from .hik_camera import HIKCamera
import cv2
import numpy as np


class ImageDetection:
    def __init__(self):
        self.current_frame: Optional[np.ndarray] = None
        self.result = False
        self.height = 0
        self.width = 0
        self.pixel_num = 0
        self.is_normal = False
        self.kill = False
        self.hik_cam = HIKCamera()
        self.hik_cam.open_camera()
        threading.Thread(target=self.get_frame_thread).start()
        threading.Thread(target=self.detect).start()

    def get_frame_thread(self):
        while not self.kill:
            frame = self.hik_cam.get_frame()
            if frame is not None:
                self.current_frame = frame
                self.height = self.current_frame.shape[0]
                self.width = self.current_frame.shape[1]
                self.pixel_num = self.height * self.width

    @staticmethod
    def display(frame: np.ndarray, text=''):
        frame = cv2.resize(frame, (800, 600), interpolation=cv2.INTER_AREA)
        final_frame = ImageDetection.put_text(frame, text)
        cv2.imshow('window', final_frame)
        cv2.waitKey(1)

    @staticmethod
    def put_text(frame: np.ndarray, text='') -> np.ndarray:
        frame_copy = copy.copy(frame)
        cv2.putText(frame_copy, text, (5, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255))
        return frame_copy

    @staticmethod
    def assert_black_screen(image: np.ndarray, black_rate: float = 0.97, black_value: int = 5,
                            smooth_rate: float = 0.01) -> tuple[bool, float]:
        result = []
        height = image.shape[0]
        width = image.shape[1]
        # 条件1 黑色像素占比
        # 转换为灰度图
        gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 将数组展开
        flatten_image = gray_image.flatten()
        # 获取黑色像素个数
        black_pixel_num = np.count_nonzero(flatten_image < black_value)
        # 计算黑色区域占比
        current_black_rate = black_pixel_num / float(height * width)
        result.append(current_black_rate < black_rate)
        # -----------------------------------------------------------------
        # 条件2 图像平滑度
        ...
        return all(result), current_black_rate

    @staticmethod
    def assert_(black_rate: float = 0.97, black_value: int = 5,
                smooth_rate: float = 0.01) -> tuple[bool, float]:
        hik = HIKCamera()
        hik.open_camera()
        while True:
            frame = hik.get_frame()
            if frame is not None:
                break
        result = ImageDetection.assert_black_screen(frame, black_rate, black_value, smooth_rate)
        hik.close_camera()
        return result

    def detect(self):
        while not self.kill:
            if self.current_frame is not None:
                self.result, _ = self.assert_black_screen(self.current_frame)
                ImageDetection.display(self.current_frame, f'{datetime.datetime.now()}{self.result}{_}')

    def kill_thread(self):
        self.kill = True
        self.hik_cam.close_camera()


if __name__ == '__main__':
    img_d = ImageDetection()
    input()
    img_d.kill_thread()
